﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BarBase : MonoBehaviour {
    public Entity entity;
    private Slider slider;
    private Slider lerp;

    private void Awake()
    {
        slider = Utils.FindChild(gameObject, "BG/Slider").GetComponent<Slider>();
        lerp = Utils.FindChild(gameObject, "BG/Lerp").GetComponent<Slider>();
        lerp.gameObject.SetActive(false);
    }

    public void UpdateHp()
    {
        slider.value = entity.Hp / (float)entity.HpMax;
    }

    public void ShowDamage(int hp, int damage, int hpMax)
    {
        lerp.gameObject.SetActive(true);
        lerp.value = hp / (float)hpMax;
        float current = (hp - damage) / (float)hpMax;
        StartCoroutine(LerpSlider(current));
    }

    IEnumerator LerpSlider(float current)
    {
        while(true)
        {
            yield return new WaitForSeconds(0.05f);
            if(lerp.value < current)
                lerp.value += 0.05f;
            else
                lerp.value -= 0.05f;
            if (Mathf.Abs(lerp.value - current) < 0.05f)
                break;
        }
    }
}
